package cn.accp.bookShop.entity.impl;

import cn.accp.bookShop.dao.BookDao;
import cn.accp.bookShop.entity.AccpBook;

public class ArrayBookDao extends BookDao {

	public ArrayBookDao() {
		this.top = 0;
		this.items = new AccpBook[10];
	}

	public ArrayBookDao(int len) {
		this.top = 0;
		if (len > 0) {
			this.items = new AccpBook[len];
		} else {
			this.items = new AccpBook[10];
		}
	}

	private int top;

	private AccpBook[] items;

	@Override
	public int getTop() {
		return top;
	}

	@Override
	public AccpBook[] getItems() {
		return items;
	}

	/**
	 * 
	 * @param id
	 *            对象的id
	 * @return id对应的索引位置，-1表示不存在
	 */

	private int indexOf(int id) {
		int index = -1;
		for (int i = 0; i < top; i++) {
			if (items[i].getId() == id) {
				index = i;
			}
		}
		return index;
	}

	@Override
	public int add(AccpBook book) {
		if (items.length == this.top) {
			return -2;
		}
		if (indexOf(book.getId()) == -1) {
			items[this.top] = book;
			this.top++;
			return 0;
		} else {
			return -1;
		}
	}

	@Override
	public int add(AccpBook book, int index) {
		if (index > this.top) {
			return -3;
		} else if (items.length == this.top) {
			return -2;
		}
		if (indexOf(book.getId()) == -1) {
			for (int i = this.top; i > index; i--) {
				items[i] = items[i - 1];
			}
			items[index] = book;
			this.top++;
			return 0;
		} else {
			return -1;
		}
	}

	@Override
	public boolean remove(int id) {
		int index = indexOf(id);// id对应的索引位置
		if (index == -1) {
			return false;
		} else {
			for (int i = index; i < top - 1; i++) {
				items[i] = items[i + 1];
			}
			this.top--;
			return true;
		}
	}

	@Override
	public boolean update(int id, double newPrice) {
		int index = indexOf(id);
		if (index > -1) {
			items[index].setPrice(newPrice);
			return true;
		} else {
			return false;
		}
	}
}
